package permission

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"github.com/super-team/start-kit/configs"
	"github.com/super-team/start-kit/middlewares/jwt"
	"github.com/super-team/start-kit/pkg/casbin"
	"github.com/super-team/start-kit/tools/log"
)

//权限检查中间件
func AuthCheckRole() gin.HandlerFunc {
	return func(c *gin.Context) {
		if configs.Config.Server.Debug {
			c.Next()
			return
		}
		user := jwt.GetAuthUser(c)
		role := jwt.GetAuthRole(c)
		if user == nil || role == nil || *role.Status == 0 || *user.Status == 0 {
			c.JSON(http.StatusOK, gin.H{
				"code": http.StatusForbidden,
				"msg":  "对不起，您没有该接口访问权限，请联系管理员",
				"data": nil,
			})
			c.Abort()
			return
		}
		//检查权限
		res, err := casbin.Permission.Enforce(*user.RoleKey, c.Request.URL.Path, c.Request.Method)
		if err != nil || !res {
			if err != nil {
				log.Log.Err(err).Send()
			}
			c.JSON(http.StatusOK, gin.H{
				"code": http.StatusForbidden,
				"msg":  "对不起，您没有该接口访问权限，请联系管理员",
				"data": nil,
			})
			c.Abort()
			return
		}
		c.Next()
	}
}
